<template>
  <div>
    <a-input ref="user_input" :disabled="disabled" :value="realname" :readOnly="true" @focus="handleClick" placeholder="请选择用户"/>
    <a-modal
      title="选择用户"
      :visible="visible"
      :width="800"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-input-search
        v-model="queryParam.realname"
        @search="searchQuery"
        placeholder="请输入真实姓名进行筛选"
        style="margin-bottom:10px;"
        />
      <a-table
        row-key="id"
        size="middle"
        :columns="columns"
        :data-source="dataSource"
        :row-selection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        bordered
      >
      </a-table>
    </a-modal>
  </div>
</template>
<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction } from '@/api/manage'
export default {
  name: 'User',
  props: ['record', 'value', 'disabled'],
  mixins: [JeecgListMixin],
  data() {
    return {
      visible: false,
      columns: [
        {
          title: '用户账号',
          dataIndex: 'username',
          key: 'username'
        },
        {
          title: '真实姓名',
          dataIndex: 'realname',
          key: 'realname'
        },
        {
          title: '角色名称',
          dataIndex: 'roleName',
          key: 'roleName'
        },
        {
          title: '性别',
          key: 'sex',
          dataIndex: 'sex'
        },
        {
          title: '手机',
          key: 'phone',
          dataIndex: 'phone'
        },
        {
          title: '邮箱',
          key: 'email',
          dataIndex: 'email'
        }
      ],
      url: {
        list: '/sys/user/list'
      },
      realname: '',
      notGetRealname: false
    }
  },
  watch: {
    value(newValue) {
      if (newValue) {
        !this.notGetRealname && this.getRealName(newValue)
      } else {
        this.realname = ''
      }
    }
  },
  methods: {
    handleClick() {
      this.$refs.user_input.blur()// 取消输入框焦点 解决弹窗重复bug
      this.visible = true
    },
    handleOk() {
      if (this.selectionRows.length <= 0) {
        this.$emit('change', '')
      } else {
        this.$emit('change', this.selectionRows[0].username)
        this.realname = this.selectionRows[0].realname
        this.notGetRealname = true
      }
      this.visible = false
    },
    handleCancel() {
      this.visible = false
    },
    onSelectChange(selectedRowKeys, selectionRows) { // 只选中一个
      this.selectedRowKeys = [selectedRowKeys.pop()]
      this.selectionRows = [selectionRows.pop()]
    },
    getRealName(username) { // 根据username获取realname
      const that = this
      getAction(this.url.list, { username: username }).then(function(res) {
        that.realname = res.result.records[0] && res.result.records[0].realname
      }).catch((error) => {
        console.log(error)
      })
    }
  },
  mounted() {
    // 打印接收的options
  }
}
</script>
